package com.uenpay.im.ui.old.activity.group;

import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.TextView;

import com.aswife.ui.MaskImageView;
import com.qiyunxin.android.http.HttpInvokeResultCode;
import com.qyx.android.database.GroupMemberManager;
import com.qyx.android.entity.FriendEntity;
import com.qyx.android.entity.GroupMemberEntity;
import com.qyx.android.message.type.PacketType;
import com.qyx.android.weight.utils.QyxWeightDensityUtils;
import com.uenpay.im.IMApplication;
import com.uenpay.im.R;
import com.uenpay.im.callback.IGetGroupMembersListener;
import com.uenpay.im.callback.IOnBottomDialogListener;
import com.uenpay.im.callback.IRemoveGroupMemberListener;
import com.uenpay.im.configuration.APIConfiguration;
import com.uenpay.im.entities.SelectedFriendEntity;
import com.uenpay.im.weight.DialogUtility;
import com.uenpay.util.app.base.BaseActivity;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Locale;

/**
 * @author SL
 * @copyRight http://www.qiyunxin.com
 */
public class DeleteGroupMemberActivity extends BaseActivity {

    private HorizontalScrollView mHorizontalScrollView;
    private LinearLayout selectedUserLayout;
    private String group_id;
    private GroupMemberManager mGroupMemberManager = new GroupMemberManager();
    private GroupMangerHandler groupMangerHandler = new GroupMangerHandler();
    private ChooseGroupMemberAdapter chooseGroupMemberAdapter = null;
    private ArrayList<SelectedFriendEntity> selectedMembers = new ArrayList<SelectedFriendEntity>();
    private ArrayList<SelectedFriendEntity> selectedFriendEntities = new ArrayList<SelectedFriendEntity>();
    private ListView pinnedListView;
    private TextView rightTextView;
    private EditText search_et;
    private View loading;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        isFullScreen = true;
        super.onCreate(savedInstanceState);
    }

    @Override
    public View bindView() {
        return null;
    }

    @Override
    public int bindLayout() {
        return R.layout.activity_delete_group_member_layout;
    }

    @Override
    public void initView(View view) {
        group_id = getIntent().getStringExtra("group_id");
        initView();
        initListener();
        initData();
        getGroupMembers();
    }

    protected void initView() {
        ((TextView) findViewById(R.id.title_textview)).setText(getResources()
                .getString(R.string.delete_group_member));
        rightTextView = ((TextView) findViewById(R.id.title_right_tv));
        rightTextView.setText(getResources().getString(R.string.delete));
        findViewById(R.id.title_right_layout).setVisibility(View.VISIBLE);
        mHorizontalScrollView = (HorizontalScrollView) findViewById(R.id.selected_users_scroll);
        selectedUserLayout = (LinearLayout) findViewById(R.id.selected_users);
        pinnedListView = (ListView) findViewById(R.id.pinnedListView);
        search_et = (EditText) findViewById(R.id.search_et);
        findViewById(R.id.choose_group_tv).setVisibility(View.GONE);
        findViewById(R.id.choose_group_view).setVisibility(View.GONE);
        loading = findViewById(R.id.loading);
    }

    protected void initListener() {
        findViewById(R.id.back_layout).setOnClickListener(
                new OnClickListener() {

                    @Override
                    public void onClick(View arg0) {
                        finish();
                    }
                });
        findViewById(R.id.title_right_layout).setOnClickListener(
                new OnClickListener() {

                    @Override
                    public void onClick(View arg0) {
                        if (selectedMembers.size() > 0) {
                            // TODO
                            String deleteCustIds = "";
                            String deleteCustNames = "";
                            for (int i = 0, size = selectedMembers.size(); i < size; i++) {
                                if (TextUtils.isEmpty(deleteCustIds)) {
                                    deleteCustIds = selectedMembers.get(i).friend.cust_id;
                                } else {
                                    deleteCustIds = deleteCustIds
                                            + ","
                                            + selectedMembers.get(i).friend.cust_id;
                                }
                                if (i <= 2) {
                                    if (TextUtils.isEmpty(deleteCustNames)) {
                                        if (!TextUtils.isEmpty(selectedMembers
                                                .get(i).friend.remarks_name)) {
                                            deleteCustNames = selectedMembers
                                                    .get(i).friend.remarks_name;
                                        } else {
                                            deleteCustNames = selectedMembers
                                                    .get(i).friend.nick_name;
                                        }
                                    } else {
                                        if (!TextUtils.isEmpty(selectedMembers
                                                .get(i).friend.remarks_name)) {
                                            deleteCustNames = deleteCustNames
                                                    + ","
                                                    + selectedMembers.get(i).friend.remarks_name;
                                        } else {
                                            deleteCustNames = deleteCustNames
                                                    + ","
                                                    + selectedMembers.get(i).friend.nick_name;
                                        }
                                    }
                                }
                            }
                            deleteGroupMembersDailog(deleteCustIds,
                                    deleteCustNames, selectedMembers.size());
                        }
                    }
                });
        pinnedListView
                .setOnItemClickListener(new AdapterView.OnItemClickListener() {

                    @Override
                    public void onItemClick(AdapterView<?> arg0, View arg1,
                                            int arg2, long arg3) {
                        SelectedFriendEntity selected = (SelectedFriendEntity) arg0
                                .getAdapter().getItem(arg2);
                        if (selectedFriendEntities.get(arg2).selectedStatus == 1) {
                            selectedFriendEntities.get(arg2).selectedStatus = 2;
                        } else {
                            selectedFriendEntities.get(arg2).selectedStatus = 1;
                        }

                        chooseGroupMemberAdapter.notifyDataSetChanged();
                        if (chooseGroupMemberAdapter
                                .isSelected(selected.friend.cust_id) == 2) {
                            selectedMembers.add(selected);
                            addSelectedFriend(selected.friend);
                        } else {
                            removeSelectedFriend(selected.friend.cust_id);
                            selectedMembers.remove(selected);
                        }

                        if (selectedMembers.size() < 1) {
                            rightTextView.setText(getResources().getString(
                                    R.string.delete));
                        } else {
                            rightTextView.setText(getResources().getString(
                                    R.string.delete)
                                    + "(" + selectedMembers.size() + ")");
                        }
                    }
                });
        search_et.addTextChangedListener(new TextWatcher() {
            @Override
            public void afterTextChanged(Editable s) {

            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {
                searchTextInUsers(s);
            }
        });
    }

    private void searchTextInUsers(CharSequence text) {
        if (text != null && text.length() > 0) {
            if (TextUtils.isEmpty(text)) {
                return;
            }
            ArrayList<SelectedFriendEntity> tempMembers = new ArrayList<SelectedFriendEntity>();
            for (SelectedFriendEntity mFriendEntity : selectedFriendEntities) {
                String charIndex = mFriendEntity.friend.nick_name;
                if (mFriendEntity.friend.nick_name.toLowerCase(Locale.getDefault()).contains(
                        text.toString().toLowerCase(Locale.getDefault()))
                        || charIndex.contains(text.toString().toLowerCase(Locale.getDefault()))) {
                    tempMembers.add(mFriendEntity);
                }
            }
            if (tempMembers.size() > 0) {
                chooseGroupMemberAdapter = new ChooseGroupMemberAdapter(
                        DeleteGroupMemberActivity.this, tempMembers);
                pinnedListView.setAdapter(chooseGroupMemberAdapter);
            } else {
                pinnedListView.setVisibility(View.GONE);
            }
        } else {
            pinnedListView.setVisibility(View.VISIBLE);
            chooseGroupMemberAdapter = new ChooseGroupMemberAdapter(
                    DeleteGroupMemberActivity.this, selectedFriendEntities);
            pinnedListView.setAdapter(chooseGroupMemberAdapter);
        }
    }

    private void initData() {
        loading.setVisibility(View.VISIBLE);
        new GetGroupMemebersAsy().execute();
    }

    private class GetGroupMemebersAsy extends AsyncTask<Void, Void, Void> {

        @Override
        protected Void doInBackground(Void... arg0) {
            selectedFriendEntities.clear();
            ArrayList<GroupMemberEntity> arrayList = queryMember();
            for (int i = 0, size = arrayList.size(); i < size; i++) {
                if (arrayList.get(i).cust_id == Long.valueOf(IMApplication
                        .getCustId())) {
                    continue;
                }
                FriendEntity friend = new FriendEntity();
                friend.cust_id = arrayList.get(i).cust_id + "";
                friend.nick_name = arrayList.get(i).nick_name;
                SelectedFriendEntity friendEntity = new SelectedFriendEntity(friend);
                selectedFriendEntities.add(friendEntity);
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            chooseGroupMemberAdapter = new ChooseGroupMemberAdapter(
                    DeleteGroupMemberActivity.this, selectedFriendEntities);
            pinnedListView.setAdapter(chooseGroupMemberAdapter);
            loading.setVisibility(View.GONE);
            super.onPostExecute(result);
        }

    }

    /**
     * @return
     */
    private ArrayList<GroupMemberEntity> queryMember() {
        ArrayList<GroupMemberEntity> list = new ArrayList<GroupMemberEntity>();
        list = mGroupMemberManager.queryAll(Long.valueOf(group_id));
        if (list.size() == 0) {

            groupMangerHandler.getGroupDetail(group_id, null);

        }
        return list;
    }

    private void removeSelectedFriend(String cust_id) {
        int pos = -1;
        for (SelectedFriendEntity friend : selectedMembers) {
            pos++;
            if (friend.friend.cust_id.equals(cust_id)) {
                break;
            }
        }

        if (pos > -1) {
            if (selectedUserLayout != null) {
                selectedUserLayout.removeViewAt(pos);
            }
            scrollToEnd();
        }
    }

    private void addSelectedFriend(FriendEntity friend) {
        MaskImageView image = new MaskImageView(DeleteGroupMemberActivity.this);

        LayoutParams lp = new LayoutParams(
                QyxWeightDensityUtils.dp2px(this, 35),
                QyxWeightDensityUtils.dp2px(this, 35));
        lp.setMargins(5, 0, 5, 0);
        image.setLayoutParams(lp);
        image.SetUrl(APIConfiguration.getAvatarUrlNormal(friend.cust_id,
                PacketType.PERSONAL));
        selectedUserLayout.addView(image);
        scrollToEnd();
    }

    public void scrollToEnd() {
        mHorizontalScrollView.postDelayed(new Runnable() {
            @Override
            public void run() {
                mHorizontalScrollView
                        .fullScroll(HorizontalScrollView.FOCUS_RIGHT);
            }
        }, 100);
    }

    private void deleteGroupMembersDailog(final String custids,
                                          String userNames, int size) {
        String content = "";
        if (size >= 4) {
            content = MessageFormat.format(
                    getResources()
                            .getString(R.string.delete_group_members_more),
                    userNames, size);
        } else {
            content = MessageFormat.format(
                    getResources().getString(R.string.delete_group_members),
                    userNames);
        }
        DialogUtility.showDialog(DeleteGroupMemberActivity.this, content,
                R.string.yes, R.string.no, true, new IOnBottomDialogListener() {

                    @Override
                    public void onClicked() {
                        deleteGroupMembers(custids);
                    }
                });
    }

    private void deleteGroupMembers(String cust_ids) {
        GroupMangerHandler groupMangerHandler = new GroupMangerHandler();
        groupMangerHandler.removeGroupMember(group_id, cust_ids,
                new IRemoveGroupMemberListener() {

                    @Override
                    public void onRemoveGroupMemberResult(int status) {
                        if (status == HttpInvokeResultCode.RESULT_OK) {
                            setResult(RESULT_OK);
                            finish();
                        }
                    }
                });
    }

    private Handler myHandler = new Handler(new Handler.Callback() {

        @Override
        public boolean handleMessage(Message msg) {
            if (msg.what == 1) {
                initData();
            }
            return false;
        }
    });

    private void getGroupMembers() {
        groupMangerHandler.getGroupMembers(group_id,
                IMApplication.getCustId(), new IGetGroupMembersListener() {

                    @Override
                    public void getGroupMembers(
                            ArrayList<GroupMemberEntity> GroupMemberEntitys) {
                        myHandler.sendEmptyMessage(1);
                    }
                });
    }

}
